﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using TomanuExtensions;

namespace AmiEmuLib.Host.HostInput
{
    /// <summary>
    /// List of all posibble event for single input device.
    /// </summary>
    public class HostEvents
    {
        /// <summary>
        /// List of events.
        /// </summary>
        private List<HostEvent> m_events = new List<HostEvent>();

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="a_resource_file"></param>
        internal HostEvents(string a_resource_file)
        {
            using (var stream = StreamExtensions.FromResource(typeof(HostEvents), a_resource_file))
            {
                XmlReaderExtensions.ReadXml(stream, (reader) =>
                {
                    reader.ReadStartElement(GetType().Name);

                    while (reader.IsStartElement())
                    {
                        HostEvent ev = new HostEvent(reader);
                        m_events.Add(ev);
                    }

                    reader.ReadEndElement();
                });
            }
        }

        /// <summary>
        /// Save to xml. For development use only.
        /// </summary>
        public void SaveToXml(string a_file)
        {
            XmlWriterExtensions.WriteXml(a_file, (writer) =>
            {
                writer.WriteStartElement(GetType().Name);

                foreach (var ev in m_events)
                    ev.WriteXml(writer);

                writer.WriteEndElement();
            });
        }

        /// <summary>
        /// Events.
        /// </summary>
        public IEnumerable<HostEvent> Events
        {
            get
            {
                return m_events;
            }
        }

        /// <summary>
        /// Add new event.
        /// </summary>
        /// <param name="a_host_event"></param>
        internal void Add(HostEvent a_host_event)
        {
            m_events.Add(a_host_event);
            m_events = m_events.OrderBy(e => e.ID).ToList();
        }

        /// <summary>
        /// Return HostEvent from event id.
        /// </summary>
        /// <param name="a_event_id"></param>
        /// <returns></returns>
        public HostEvent GetEvent(int a_event_id)
        {
            return m_events.FirstOrDefault(ev => ev.ID == a_event_id);
        }
    }
}
